<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Story
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */


class Story_PhotoController extends Core_Controller_Action_Standard
{
	public function init()
	{	
		if( !Engine_Api::_()->core()->hasSubject() )
		{
			if( 0 !== ($photo_id = (int) $this->_getParam('photo_id')) &&
					null !== ($photo = Engine_Api::_()->getItem('story_photo', $photo_id)) )
			{
				Engine_Api::_()->core()->setSubject($photo);
			}

			else if( 0 !== ($story_id = (int) $this->_getParam('story_id')) &&
					null !== ($story = Engine_Api::_()->getItem('story', $story_id)) )
			{
				Engine_Api::_()->core()->setSubject($story);
			}
		}
		
		$this->_helper->requireUser->addActionRequires(array(
				'upload',
				'upload-photo',
				'edit',
				'delete',
				'manage',
				'add-bubble',
				'edit-bubble',
				'delete-bubble',
				'get-bubbles'
		));

		$this->_helper->requireSubject->setActionRequireTypes(array(
				'list' => 'story',
				'upload' => 'story',
				'view' => 'story_photo',
				'edit' => 'story_photo',
				'delete' => 'story_photo',
				'add-bubble' => 'story_photo',
				'edit-bubble' => 'story_photo',
				'delete-bubble' => 'story_photo',
				'get-bubbles' => 'story_photo',
				'manage' => 'story',
		));		
		
	}

	public function listAction()
	{
		$this->view->story = $story = Engine_Api::_()->core()->getSubject();
		$this->view->album = $album = $story->getSingletonAlbum();

		$this->view->paginator = $paginator = $album->getCollectiblesPaginator();
		$paginator->setCurrentPageNumber($this->_getParam('page', 1));

		$this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
		$this->view->owner = $owner = Engine_Api::_()->getItem('user', $story->owner_id);

		$this->view->canUpload = $this->_helper->requireAuth()->setAuthParams($story, null, 'photo')->checkRequire();

		$album->view_count++;
		$album->save();
	}



	public function manageAction()
	{
		$this->view->story = $story = Engine_Api::_()->core()->getSubject();

		if( !$this->_helper->requireAuth()->setAuthParams($story, null, 'photo')->isValid() ) return;

		//echo 'stupid';
		//if( !$this->_helper->requireUser()->isValid() ) return;
		//if( !$this->_helper->requireAuth()->setAuthParams($story, null, 'edit')->isValid() ) return;

		$viewer = Engine_Api::_()->user()->getViewer();
		//$this->view->canUpload = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'story', 'photo');


		// Prepare data
		$this->view->story = $story = Engine_Api::_()->core()->getSubject();
		$this->view->album = $album = $story->getSingletonAlbum();
		$this->view->paginator = $paginator = $album->getCollectiblesPaginator();

		$paginator->setCurrentPageNumber($this->_getParam('page',1));
		$paginator->setItemCountPerPage($paginator->getTotalItemCount());

		// Make form
		$this->view->form = $form = new Story_Form_Photo_Manage();

		//$form->addNotice(Zend_Registry::get('Zend_Translate')->_('Your changes were saved.'));

		foreach( $paginator as $photo )
		{
			$subform = new Story_Form_Photo_Manage_Edit(array('elementsBelongTo' => $photo->getGuid()));
			$subform->populate($photo->toArray());
			$form->addSubForm($subform, $photo->getGuid());
			$form->cover->addMultiOption($photo->file_id, $photo->file_id);
		}

		if( !$this->getRequest()->isPost() )
		{
			return;
		}

		if( !$form->isValid($this->getRequest()->getPost()))
		{
			return;
		}

		$table = $story->getTable();
		$db = $table->getAdapter();
		$db->beginTransaction();

		try
		{
			$values = $form->getValues();
			if( !empty($values['cover']) ) {
				$story->photo_id = $values['cover'];
				$story->save();
			}


			// Process
			foreach( $paginator as $photo )
			{
				$subform = $form->getSubForm($photo->getGuid());
				$values = $subform->getValues();

				$values = $values[$photo->getGuid()];
				unset($values['photo_id']);
				if( isset($values['delete']) && $values['delete'] == '1' )
				{
					$photo->delete();
				}
				else
				{
					$photo->setFromArray($values);
					$photo->save();
				}
			}

			$db->commit();
		}

		catch( Exception $e )
		{
			$db->rollBack();
			throw $e;
		}

		return $this->_helper->redirector->gotoRoute(array('controller'=>'photo', 'action' => 'list', 'subject' => $story->getGuid()), 'story_extended', true);

	}


	public function uploadAction()
	{
		if( isset($_GET['ul']) || isset($_FILES['Filedata']) ) {
			return $this->_forward('upload-photo', null, null, array('format' => 'json'));
		}

		$this->view->story = $story = Engine_Api::_()->core()->getSubject();
		if( !$this->_helper->requireAuth()->setAuthParams($story, null, 'photo')->isValid() ) {
			return;
		}

		$viewer = Engine_Api::_()->user()->getViewer();
		$album = $story->getSingletonAlbum();

		$this->view->story_id = $story->story_id;
		$this->view->form = $form = new Story_Form_Photo_Upload();
		$form->file->setAttrib('data', array('story_id' => $story->getIdentity()));

		if( !$this->getRequest()->isPost() )
		{
			return;
		}

		if( !$form->isValid($this->getRequest()->getPost()) )
		{
			return;
		}

		// Process
		$table = Engine_Api::_()->getItemTable('story_photo');
		$db = $table->getAdapter();
		$db->beginTransaction();

		try
		{
			$values = $form->getValues();
			$params = array(
					'story_id' => $story->getIdentity(),
					'user_id' => $viewer->getIdentity(),
			);

			// Add action and attachments
			$api = Engine_Api::_()->getDbtable('actions', 'activity');
			$action = $api->addActivity(Engine_Api::_()->user()->getViewer(), $story, 'story_photo_upload', null, array(
					'count' => count($values['file'])
			));

			// Do other stuff
			$count = 0;
			foreach( $values['file'] as $photo_id )
			{
				$photo = Engine_Api::_()->getItem("story_photo", $photo_id);
				if( !($photo instanceof Core_Model_Item_Abstract) || !$photo->getIdentity() ) continue;

				$photo->collection_id = $album->album_id;
				$photo->album_id = $album->album_id;
				$photo->save();


				if ($story->photo_id == 0) {
					$story->photo_id = $photo->file_id;
					$story->save();
				}


				if( $action instanceof Activity_Model_Action && $count < 8 )
				{
					$api->attachActivity($action, $photo, Activity_Model_Action::ATTACH_MULTI);
				}
				$count++;
			}

			$db->commit();
		}

		catch( Exception $e )
		{
			$db->rollBack();
			throw $e;
		}


		$this->_redirectCustom($story);
	}

	public function uploadPhotoAction()
	{
		$story = Engine_Api::_()->getItem('story', (int) $this->_getParam('story_id'));

		if( !$this->_helper->requireUser()->checkRequire() )
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Max file size limit exceeded (probably).');
			return;
		}

		if( !$this->getRequest()->isPost() )
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
			return;
		}

		// @todo check auth
		//$story

		$values = $this->getRequest()->getPost();
		if( empty($values['Filename']) )
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('No file');
			return;
		}

		if( !isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name']) )
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid Upload');
			return;
		}

		$db = Engine_Api::_()->getDbtable('photos', 'story')->getAdapter();
		$db->beginTransaction();

		try
		{
			$viewer = Engine_Api::_()->user()->getViewer();
			$album = $story->getSingletonAlbum();

			$params = array(
					// We can set them now since only one album is allowed
					'collection_id' => $album->getIdentity(),
					'album_id' => $album->getIdentity(),

					'story_id' => $story->getIdentity(),
					'user_id' => $viewer->getIdentity(),
			);

			$photoTable = Engine_Api::_()->getItemTable('story_photo');
			$photo = $photoTable->createRow();
			$photo->setFromArray($params);
			$photo->save();

			$photo->setPhoto($_FILES['Filedata']);

			//$photo_id = Engine_Api::_()->story()->createPhoto($params, $_FILES['Filedata'])->photo_id;

			$this->view->status = true;
			$this->view->name = $_FILES['Filedata']['name'];
			$this->view->photo_id = $photo->getIdentity();

			$db->commit();
		}

		catch( Exception $e )
		{
			$db->rollBack();
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('An error occurred.');
			// throw $e;
			return;
		}
	}



	public function viewAction()
	{
		$this->view->photo = $photo = Engine_Api::_()->core()->getSubject();
		$this->view->album = $album = $photo->getCollection();
		$this->view->story = $story = $photo->getStory();

		$this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();

		$this->view->canUpload = $this->_helper->requireAuth()->setAuthParams($story, null, 'photo')->checkRequire();

		$photo->view_count++;
		$photo->save();
	}



	public function editAction()
	{
		 
		$photo = Engine_Api::_()->core()->getSubject();

		$this->view->story = $story = $photo->getStory();
		if( !$this->_helper->requireAuth()->setAuthParams($story, null, 'photo')->isValid() ) return;

		$this->view->form = $form = new Story_Form_Photo_Edit();

		if( !$this->getRequest()->isPost() )
		{
			$form->populate($photo->toArray());
			return;
		}

		if( !$form->isValid($this->getRequest()->getPost()) )
		{
			return;
		}

		// Process
		$db = Engine_Api::_()->getDbtable('photos', 'story')->getAdapter();
		$db->beginTransaction();

		try
		{
			$photo->setFromArray($form->getValues())->save();

			$db->commit();
		}

		catch( Exception $e )
		{
			$db->rollBack();
			throw $e;
		}

		return $this->_forward('success', 'utility', 'core', array(
				'messages' => array(Zend_Registry::get('Zend_Translate')->_('Changes saved')),
				'layout' => 'default-simple',
				'parentRefresh' => true,
				'closeSmoothbox' => true,
		));
	}



	public function deleteAction()
	{
		$photo = Engine_Api::_()->core()->getSubject();
		$this->view->story = $story = $photo->getParent('story');

		if( !$this->_helper->requireAuth()->setAuthParams($story, null, 'photo')->isValid() ) return;

		$this->view->form = $form = new Story_Form_Photo_Delete();

		if( !$this->getRequest()->isPost() )
		{
			$form->populate($photo->toArray());
			return;
		}

		if( !$form->isValid($this->getRequest()->getPost()) )
		{
			return;
		}

		// Process
		$db = Engine_Api::_()->getDbtable('photos', 'story')->getAdapter();
		$db->beginTransaction();

		try
		{
			$photo->delete();

			$db->commit();
		}

		catch( Exception $e )
		{
			$db->rollBack();
			throw $e;
		}

		$parentRedirect = Zend_Controller_Front::getInstance()->getRouter()
		->assemble(array('controller'=>'photo', 'action' => 'list', 'subject' => $story->getGuid()), 'story_extended', true);

		return $this->_forward('success', 'utility', 'core', array(
				'messages' => array(Zend_Registry::get('Zend_Translate')->_('Photo deleted')),
				'layout' => 'default-simple',
				'parentRedirect' => $parentRedirect,
				'closeSmoothbox' => true,
		));

	}

	
	/**
	 * Add bubble for a photo
	 */
	public function saveBubbleAction(){
		$photo_id = $this->_getParam('photo_id');
		
		$bubble = array();		
		$values = $_GET;
		
		$bubbleTable =  Engine_Api::_()->getDbtable('bubbles', 'story');
		if(count($values) > 0){
			try {
				$id = isset($values['id']) ? $values['id'] : "";
				unset($values['id']);
				if($id == "new"){
					$item = $bubbleTable->createRow();
				}else {
					$item = Engine_Api::_()->getItem('story_bubble', $id);
					if(!$item){
						echo Zend_Json::encode($bubble);
						die();
					}
				}
				$item->setFromArray($values);
				$item->title = $values['text'];
				$item->photo_id = $photo_id;
				$item->editable = 1;
				$item->save();
				
				$bubble = $item->toArrayEx();
			} catch(Exception $e){
				//Do nothing here
			}			
		}
		
		echo Zend_Json::encode($bubble);
		die();
	}

	
	/**
	 * Delete bubble for a photo
	 */
	public function deleteBubbleAction(){
		$photo_id = $this->_getParam('photo_id');
		
		$bubble = array('status' => false);
		$values = $_GET;		
		$id = isset($values['id']) ? $values['id'] : ""; 
		
		$item = Engine_Api::_()->getItem('story_bubble', $id);
		if(!$item){
			echo Zend_Json::encode($bubble);
			die();
		} else {
			$item->delete();
			$bubble['status'] = true;
		}
		
		echo Zend_Json::encode($bubble);
		die();
	}
	
	/**
	 * List bubbles for a photo
	 */
	public function getBubblesAction(){
		//die("fasdfsadf");
		$photo_id = $this->_getParam('photo_id');
		
		$bubbles = array();
		if(!empty($photo_id)){
			$bubbleTable =  Engine_Api::_()->getDbtable('bubbles', 'story');
			$bubbles = $bubbleTable->getBubbles($photo_id);
		}		
		
		//$data = array();
		echo Zend_Json::encode($bubbles);
		die();
	}

}